<template>
	<div class=" pt-0 h-full overflow-hidden">
		<scroll-view :scroll-top="scrollTop" scroll-y="true" class="scroll-Y w-full h-full overflow-hidden"
			@scrolltolower="onScrollToLower">
			<view class="container !pt-[30px]">
				<view v-for="colNum in state.columnNum" :key="colNum" class="columnItem">
					<child-item v-for="(item, i) in state.columnData[colNum]" :key="i" :item="item" @load="imageLoad($event, item)"
						@click.stop="$emit('itemClick', item)" />
				</view>
			</view>
			<view class="loading text-[36px]" v-show="state.showMoreLoading">加载中…</view>
		</scroll-view>
	</div>
</template>

<script setup>
	import {
		ref,
		reactive,
		getCurrentInstance
	} from "vue";
	import childItem from "./child-item.vue";
	import {
		onMounted
	} from "vue";
	const Instance = getCurrentInstance();
	const scrollTop = ref(0);
	const state = reactive({
		columnNum: 3,
		minHeightColNum: 1,
		columnData: {},
		totalList: [],
		showMoreLoading: true,
		noMore: false,
		pages: {
			page: 0,
			pageSize: 20,
		},
		data: [],
	});

	function getData() {
		return new Promise((resolve) => {
			setTimeout(() => {
				state.totalList.push(
					...state.data.slice(
						state.pages.page * state.pages.pageSize,
						(state.pages.page + 1) * state.pages.pageSize
					)
				);
				loadNextItem();
				resolve();
			}, 500);
		});
	}

	onMounted(() => {
		uni.request({
			url: import.meta.env.VITE_APP_PREFIX + "/static/data/img.json",
			data: {
				time : new Date().getTime()
			},
			noCache: true
		}).then((res) => {
			state.data = res.data.map(v => {
				return {
					...v,
					cover: import.meta.env.VITE_APP_PREFIX + v.cover,
					img: v.img.map(v => import.meta.env.VITE_APP_PREFIX + v),
					width: undefined
				}
			})
			setDefaultData();
			getData();
		});
	});

	/** @加载更多 **/
	async function onScrollToLower() {
		if (state.data.length == state.totalList.length) {
			state.showMoreLoading = false;
			state.noMore = true;
			return;
		}
		if (state.showMoreLoading) return
		state.showMoreLoading = true;
		state.pages.page++;
		await getData();
		state.showMoreLoading = false;
	}

	/** @图片加载成功 **/
	function imageLoad(e, item) {
		const detail = e.detail
		if(detail.height > 400) {
			item.width = Math.ceil((400 / detail.height) *  detail.width)
		}
		getMinHeightColumnNum().then(() => loadNextItem());
	}

	/** @加载下一个元素 **/
	function loadNextItem() {
		const totalLength = Object.values(state.columnData).flat().length;
		if (totalLength == state.totalList.length) {
			state.showMoreLoading = false;
			return;
		}
		state.columnData[state.minHeightColNum].push(state.totalList[totalLength]);
	}
	/** @设置默认数据 **/
	function setDefaultData() {
		state.totalList = [];
		Array(state.columnNum)
			.fill(null)
			.map((item, i) => {
				state.columnData[i + 1] = [];
			});
	}
	/** @获取最小列数 **/
	async function getMinHeightColumnNum() {
		let minHeight = Infinity; // 初始化为无限大
		return new Promise((resolve) => {
			$(".columnItem", Instance).then((columItems) => {
				columItems.forEach((item, index) => {
					if (item.height < minHeight) {
						minHeight = item.height;
						state.minHeightColNum = index + 1;
					}
				});
				resolve();
			});
		});
	}

	function $(selecter, proxy) {
		return new Promise((resolve) => {
			uni.createSelectorQuery().in(proxy).selectAll(selecter).boundingClientRect().exec((res) => {
				resolve(res[0]);
			});
		});
	}
</script>

<style lang="scss" scoped>
	.container {
		display: flex;
		padding: 0 50px 50px;

		.columnItem {
			width: calc((100% - 50px)/ v-bind("state.columnNum"));
			height: fit-content;

			&+.columnItem {
				margin-left: 29px;
			}
		}
	}

	.loading {
		padding: 20px;
		text-align: center;
		color: #aaa;
	}
</style>